import 'package:shared_preferences/shared_preferences.dart';

// 缓存管理工具
class HiCache {
  SharedPreferences? prefs;
  static HiCache? _instance;

  //#region 单例模式，先调用 preInit 再调用 getInstance
  HiCache._pre(this.prefs);

  // 构造方法，用于创建单例的本类对象
  HiCache._(){
    init();
  }

  static Future<HiCache?> preInit() async {
    if(_instance == null){
      var prefs = await SharedPreferences.getInstance();
      _instance = HiCache._pre(prefs);
    }
    return _instance;
  }

  static HiCache getInstance() {
    _instance ??= HiCache._();
    return _instance!;
  }

  void init() async {
    prefs ??= await SharedPreferences.getInstance();
  }
  //#endregion

  //#region setter
  setString(String key,String val){
    prefs?.setString(key, val);
  }
  setDouble(String key,double val){
    prefs?.setDouble(key, val);
  }
  setInt(String key,int val){
    prefs?.setInt(key, val);
  }
  setBool(String key,bool val){
    prefs?.setBool(key, val);
  }
  setStringList(String key,List<String> val)){
    prefs?.setStringList(key, val);
  }
  //#endregion

  void remove(String key){
    prefs?.remove(key);
  }

  // 泛型的方式获取 kv
  T? get<T>(String key){
    var data = prefs?.get(key);
    if(data == null) return null;
    return data as T;
  }
}